package com.paipaideli.ui.mine.address;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.PullRefreshView;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.ui.mine.address.bean.AddressBean;
import com.paipaideli.ui.mine.order.OrderDetailActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 收货地址
 */
public class AddAddressActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.address_recycleview)
    PullRefreshView address_recycleview;
    @BindView(R.id.btn_addaddress)
    Button btn_addaddress;

    private AddAdderssAdapter addAdderssAdapter;
    private List<AddressBean.Data> list = new ArrayList<>();

    private boolean flag;
    private String whichOne;

    @Override
    public int getContentView() {
        return R.layout.activity_addaddress;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        top_title.setText("收货地址");

        whichOne = getIntent().getStringExtra("which");

        address_recycleview.setEnableRefresh(false);
        address_recycleview.setEnableLoadmore(false);
        addAdderssAdapter = new AddAdderssAdapter();
        address_recycleview.setLayoutManager(new LinearLayoutManager(this));
        address_recycleview.setAdapter(addAdderssAdapter);

        //新增收货地址
        addDisposable(RxView.clicks(btn_addaddress)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    Intent intent = new Intent(AddAddressActivity.this, ModifyAddressActivity.class);
                    intent.putExtra("which", "1");
                    startActivity(intent);
                }));

        //返回
        top_back.setOnClickListener(o ->
                finish()
        );
    }

    @Override
    protected void onStart() {
        super.onStart();
        initDate();
    }

    public void initDate() {
        JSONObject requestData = new JSONObject();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().addressList(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.code.equals("200")) {
                        list.clear();
                        list = request.data;
                        addAdderssAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }

    public class AddAdderssAdapter extends RecyclerView.Adapter {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(AddAddressActivity.this).inflate(R.layout.item_address_view, null);
            inflate.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return new ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            AddAdderssAdapter.ViewHolder viewHolder = (ViewHolder) holder;
            viewHolder.tv_address_name.setText(list.get(position).name);
            viewHolder.tv_address_phone.setText(list.get(position).phone);
            viewHolder.tv_address_add.setText(list.get(position).province + list.get(position).city + list.get(position).area + list.get(position).address);
            if (list.get(position).isUse.equals("1")) {
                flag = true;
                viewHolder.image_address_mr.setBackgroundResource(R.mipmap.login_check);
            } else {
                flag = false;
                viewHolder.image_address_mr.setBackgroundResource(R.mipmap.login_nocheck);
            }

            //默认地址设置
            RxView.clicks(viewHolder.rel_add_mr).subscribe(o -> {
                if (flag) {
                    flag = false;
                    viewHolder.image_address_mr.setBackgroundResource(R.mipmap.login_nocheck);
                } else {
                    flag = true;
                    viewHolder.image_address_mr.setBackgroundResource(R.mipmap.login_check);
                }
                String id = list.get(position).id;
                setIsUse(id);
            }, throwable -> {
            });

            //编辑地址
            RxView.clicks(viewHolder.rel_address_edit).subscribe(o -> {
                Intent intent = new Intent(AddAddressActivity.this, ModifyAddressActivity.class);
                intent.putExtra("which", "2");
                intent.putExtra("id", list.get(position).id);
                intent.putExtra("name", list.get(position).name);
                intent.putExtra("phone", list.get(position).phone);
                intent.putExtra("province", list.get(position).province);
                intent.putExtra("city", list.get(position).city);
                intent.putExtra("area", list.get(position).area);
                intent.putExtra("address", list.get(position).address);
                intent.putExtra("isUse", list.get(position).isUse);
                startActivity(intent);
            }, throwable -> {
            });

            //删除地址
            RxView.clicks(viewHolder.rel_address_del).subscribe(o -> {
                String id = list.get(position).id;
                delAddress(id);
//                list.remove(position);//删除数据源,移除集合中当前下标的数据
//                notifyItemRemoved(position);//刷新被删除的地方
//                notifyItemRangeChanged(position, getItemCount()); //刷新被删除数据，以及其后面的数据
            }, throwable -> {

            });

            //地址跳转
            RxView.clicks(viewHolder.lin_ietm_add).subscribe(o -> {
                if (whichOne.equals("1")) {
                    Intent intent = new Intent(AddAddressActivity.this, OrderDetailActivity.class);
                    intent.putExtra("addId", list.get(position).id);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }, throwable -> {
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.tv_address_name)
            TextView tv_address_name;
            @BindView(R.id.tv_address_phone)
            TextView tv_address_phone;
            @BindView(R.id.tv_address_add)
            TextView tv_address_add;
            @BindView(R.id.image_address_mr)
            ImageView image_address_mr;
            @BindView(R.id.rel_address_edit)
            RelativeLayout rel_address_edit;
            @BindView(R.id.rel_address_del)
            RelativeLayout rel_address_del;
            @BindView(R.id.rel_add_mr)
            RelativeLayout rel_add_mr;
            @BindView(R.id.lin_ietm_add)
            LinearLayout lin_ietm_add;

            public ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    //删除地址
    private void delAddress(String id) {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("id", id);
            requestData.put("isDel", "1");
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().updateAddress(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.getCode().equals("200")) {
                        initDate();
                        ToastUtil.show(request.getMessage());
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }

    //设置默认
    private void setIsUse(String id) {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("id", id);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().addisUse(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.getCode().equals("200")) {
                        initDate();
                        ToastUtil.show(request.getMessage());
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }
}
